package com.trsj.lnsj.util;

import java.awt.AlphaComposite;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.Rectangle;
import java.awt.RenderingHints;
import java.awt.Transparency;
import java.awt.geom.Ellipse2D;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import javax.imageio.ImageIO;
import javax.imageio.stream.ImageInputStream;
import javax.imageio.stream.MemoryCacheImageInputStream;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 将图片圆角化处理工具类
 * 
 * @author lenovo
 *
 */
public class MakeRoundedCornerUtil {
  private static Logger logger = LoggerFactory.getLogger(MakeRoundedCornerUtil.class);

  /**
   * 图片圆角处理，背景透明化
   * 
   * @param srcImageFile 原图片
   * @param result 处理后图片
   * @param type 图片格式
   * @param cornerRadius 720为圆角
   */
  public static void makeRoundedCorner(BufferedImage bi1, File result, String type,
      int cornerRadius) {
    try {
      if (null == bi1) {
        return;
      }
      logger.info("reminder_message={}", "makeRoundedCorner start execute");
      // 根据需要是否使用 BufferedImage.TYPE_INT_ARGB
      BufferedImage image =
          new BufferedImage(bi1.getWidth(), bi1.getHeight(), BufferedImage.TYPE_INT_ARGB);

      Ellipse2D.Double shape = new Ellipse2D.Double(0, 0, bi1.getWidth(), bi1.getHeight());

      Graphics2D g2 = image.createGraphics();
      image = g2.getDeviceConfiguration().createCompatibleImage(bi1.getWidth(), bi1.getHeight(),
          Transparency.TRANSLUCENT);
      g2 = image.createGraphics();
      g2.setComposite(AlphaComposite.Clear);
      g2.fill(new Rectangle(image.getWidth(), image.getHeight()));
      g2.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC, 1.0f));
      g2.setClip(shape);
      // 使用 setRenderingHint 设置抗锯齿
      g2 = image.createGraphics();
      g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
      g2.fillRoundRect(0, 0, bi1.getWidth(), bi1.getHeight(), cornerRadius, cornerRadius);
      g2.setComposite(AlphaComposite.SrcIn);
      g2.drawImage(bi1, 0, 0, bi1.getWidth(), bi1.getHeight(), null);
      g2.dispose();
      logger.info("outfilePath={}", result.getAbsolutePath());
      ImageIO.write(image, type, result);
    } catch (Exception e) {
      logger.info("error_message={}", e.getMessage());
      e.printStackTrace();
    }
  }

  /**
   * 按照 宽高 比例压缩
   * 
   * @param img
   * @param width
   * @param height
   * @param out
   * @throws IOException
   */
  public static BufferedImage thumbnail_w_h(String urlStr, int width, int height)
      throws IOException {
    logger.info("url_param={}", urlStr);
    URL url = new URL(urlStr);
    // 打开链接
    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
    // 设置请求方式为"GET"
    conn.setRequestMethod("GET");
    // 超时响应时间为5秒
    conn.setConnectTimeout(5 * 1000);
    // 通过输入流获取图片数据
    InputStream inStream = conn.getInputStream();
    //得到图片的二进制数据，以二进制封装得到数据，具有通用性 
    byte[] imgBytes = null;
    try {
      imgBytes = readInputStream(inStream);
      // 将字节数组转为InputStream，再转为MemoryCacheImageInputStream
      ImageInputStream imageInputstream = new MemoryCacheImageInputStream(new ByteArrayInputStream(imgBytes));
      BufferedImage bi = ImageIO.read(imageInputstream);
      logger.info("url_BufferedImage is null={}", bi == null);
      double srcWidth = bi.getWidth(); // 源图宽度
      double srcHeight = bi.getHeight(); // 源图高度
      double scale = 1;
      
      if (width > 0) {
        scale = width / srcWidth;
      }
      if (height > 0) {
        scale = height / srcHeight;
      }
      if (width > 0 && height > 0) {
        scale = height / srcHeight < width / srcWidth ? height / srcHeight : width / srcWidth;
      }
      logger.info("thumbnail_w_h={}", "thumbnail_w_h end");
      return thumbnail(bi, (int) (srcWidth * scale), (int) (srcHeight * scale));
    } catch (Exception e) {
      e.printStackTrace();
    }
    return null;
  }

  /**
   * 从图片流中读取出二进制
   * @param inStream
   * @return
   * @throws Exception
   */
  public static byte[] readInputStream(InputStream inStream) throws Exception {
    ByteArrayOutputStream outStream = new ByteArrayOutputStream();
    // 创建一个Buffer字符串
    byte[] buffer = new byte[1024];
    // 每次读取的字符串长度，如果为-1，代表全部读取完毕
    int len = 0;
    // 使用一个输入流从buffer里把数据读取出来
    while ((len = inStream.read(buffer)) != -1) {
      // 用输出流往buffer里写入数据，中间参数代表从哪个位置开始读，len代表读取的长度
      outStream.write(buffer, 0, len);
    }
    // 关闭输入流
    inStream.close();
    // 把outStream里的数据写入内存
    return outStream.toByteArray();
  }

  /**
   * 按照固定宽高原图压缩
   *
   * @param img
   * @param width
   * @param height
   * @throws IOException
   */
  public static BufferedImage thumbnail(BufferedImage bi, int width, int height)
      throws IOException {
    logger.info("thumbnail_reminder_message={}", "thumbnail start execute");
    if (null == bi) {
      return null;
    }
    Image image = bi.getScaledInstance(width, height, Image.SCALE_SMOOTH);

    BufferedImage tag = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
    Graphics g = tag.getGraphics();
    g.setColor(Color.RED);
    g.drawImage(image, 0, 0, null); // 绘制处理后的图
    g.dispose();
    return tag;
  }
}
